<script setup lang="ts">
import { YkLogin, utils } from 'yklib'
import router from '../router'
import { onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useToolStore } from '../stores/tool'


const {
  serverHost,
  serverPort,
  isLogin,
  currentUsername,
  currentUserEmail,
  money,
  vip,
  lastLogin,
  lastTickTime,
  appName
} = storeToRefs(useToolStore())
const host = `${serverHost.value}:${serverPort.value}`

const login = async (username: string, password: string) => {
  const user = await utils.login(host, username, password, appName.value)

  if (user && user.isLogin) { // 如果登录成功
    currentUsername.value = user.username!
    currentUserEmail.value = user.email!
    money.value = user.money!
    vip.value = user.vip!
    lastLogin.value = user.lastLogin!
    isLogin.value = user.isLogin! as any
    lastTickTime.value = '' // 如果更换了用户登录，lastTickTime需要清空，以使心跳函数可以重新触发，从而正常扣费
    await router.push('./home')
  }
}

const register = async (username: string, password: string, email?: string) => {
  await utils.register(host, username, password, email, appName.value)
}

const color1 = '#fff'
const color2 = 'coral'
const color3 = 'black'
onMounted(() => {
  // 判断当前用户是否已经登录，如果已经登录，则直接跳转到功能页面
  if (isLogin.value) {
    router.push('./home')
  }
})
</script>

<template>
  <YkLogin :loginFn="login" :registerFn="register" :background1="color1" :text-color="color3"
           :background2="color2" login-text2="Stocks同步服务">
  </YkLogin>
</template>

<style scoped>

</style>